package com.atguigu.utils;


//未来任何JDBC方式访问的数据库,任何查询都可以使用当前的工具类

import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.GmallConfig;
import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * select count(*) from t;                   单行单列
 * select sex from t;                        多行单列
 * select * from t where id = '1001';        单行多列
 * select * from t;                          多行多列
 */
public class JdbcUtil {

    public static <T> List<T> queryList(Connection connection, String querySql, Class<T> clz, boolean underScoreToCamel) throws SQLException, IllegalAccessException, InstantiationException, InvocationTargetException {

        //创建集合存放最终结果
        ArrayList<T> resultList = new ArrayList<>();

        //编译SQL
        PreparedStatement preparedStatement = connection.prepareStatement(querySql);

        //执行查询
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();

        //遍历结果集,将每行数据封装为T对象
        while (resultSet.next()) {

            //创建T对象
            T t = clz.newInstance();

            //遍历单行数据中的列,获取列名和值赋值给T对象
            for (int i = 0; i < columnCount; i++) {
                String columnName = metaData.getColumnName(i + 1);
                Object value = resultSet.getObject(columnName);
                //对列名进行转换
                if (underScoreToCamel) {
                    columnName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName.toLowerCase());
                }
                BeanUtils.setProperty(t, columnName, value);
            }

            //将T对象添加至集合
            resultList.add(t);
        }

        resultSet.close();
        preparedStatement.close();

        //返回结果
        return resultList;
    }

    public static void main(String[] args) throws Exception {

        Connection connection = DriverManager.getConnection(GmallConfig.PHOENIX_SERVER);

        List<JSONObject> queryList = queryList(connection,
                "select * from GMALL210927_REALTIME.DIM_BASE_TRADEMARK",
                JSONObject.class,
                true);

        for (JSONObject jsonObject : queryList) {
            System.out.println(jsonObject);
        }

        connection.close();

    }

}
